package com.xxd.dfs.client;

import com.xxd.dfs.namenode.rpc.model.AllocateDataNodesRequest;
import com.xxd.dfs.namenode.rpc.model.AllocateDataNodesResponse;
import com.xxd.dfs.namenode.rpc.model.CreateFileRequest;
import com.xxd.dfs.namenode.rpc.model.CreateFileResponse;
import com.xxd.dfs.namenode.rpc.model.MkdirRequest;
import com.xxd.dfs.namenode.rpc.model.MkdirResponse;
import com.xxd.dfs.namenode.rpc.model.ShutdownRequest;
import com.xxd.dfs.namenode.rpc.service.NameNodeServiceGrpc;
import io.grpc.ManagedChannel;
import io.grpc.netty.NegotiationType;
import io.grpc.netty.NettyChannelBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author: XiaoDong.Xie
 * @create: 2020-09-07 09:29
 * @description: namenode 代理
 */
public class NameNodeClient {
    private static final Logger logger = LoggerFactory.getLogger(NameNodeClient.class);

    private NameNodeServiceGrpc.NameNodeServiceBlockingStub namenode;

    public NameNodeClient(String nameNodeIp, int port) {
        ManagedChannel channel = NettyChannelBuilder
                .forAddress(nameNodeIp, port)
                .negotiationType(NegotiationType.PLAINTEXT)
                .build();

        this.namenode = NameNodeServiceGrpc.newBlockingStub(channel);
    }

    /**
     * 创建路劲
     *
     * @param path 绝对路劲
     * @return
     */
    public boolean mkdir(String path) {
        MkdirRequest request = MkdirRequest.newBuilder()
                .setPath(path)
                .build();

        MkdirResponse response = namenode.mkdir(request);

        return response.getStatus() == 1;
    }

    /**
     * 关闭namendoe
     */
    public void shutdown() {
        ShutdownRequest request = ShutdownRequest.newBuilder()
                .setCode(1).build();
        namenode.shutdown(request);
    }

    /**
     * 发送请求到master节点创建文件
     *
     * @param filename
     * @return
     */
    public boolean createFile(String filename) {
        CreateFileRequest request = CreateFileRequest.newBuilder()
                .setFilename(filename)
                .build();
        CreateFileResponse response = namenode.create(request);


        return response.getStatus() == 1;
    }

    /**
     * 请求分配datanode
     * @param fileInfo
     * @return
     */
    public String allocateDataNodes(FileInfo fileInfo) {
        AllocateDataNodesRequest request = AllocateDataNodesRequest.newBuilder()
                .setFilename(fileInfo.getFileName())
                .setFileSize(fileInfo.getFileLength())
                .build();

        AllocateDataNodesResponse response = namenode.allocateDataNodes(request);
        return response.getDatanodes();
    }


}
